package com.imooc.sellspringcloud.server.service.impl;


import com.imooc.product.common.DecreaseStockInput;
import com.imooc.product.common.ProductInfoOutput;
import com.imooc.sellspringcloud.client.ProductClient;
import com.imooc.sellspringcloud.server.dataobject.OrderDetail;
import com.imooc.sellspringcloud.server.dataobject.OrderMaster;
import com.imooc.sellspringcloud.server.dto.OrderDTO;
import com.imooc.sellspringcloud.server.enums.OrderExceptionEnum;
import com.imooc.sellspringcloud.server.enums.OrderPayStatusEnum;
import com.imooc.sellspringcloud.server.enums.OrderStatusEnum;
import com.imooc.sellspringcloud.server.exception.OrderException;
import com.imooc.sellspringcloud.server.repository.OrderDetailRepository;
import com.imooc.sellspringcloud.server.repository.OrderMasterRepository;
import com.imooc.sellspringcloud.server.service.OrderService;
import com.imooc.sellspringcloud.server.utils.KeyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author
 * @create 2019-07-27 21:48
 **/
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    OrderDetailRepository detailRepository;
    @Autowired
    OrderMasterRepository masterRepository;
    @Autowired
    RestTemplate restTemplate;

    @Autowired
    ProductClient productClient;

    @Override
    @Transactional
    public OrderDTO create(OrderDTO orderDTO) {
        //查询商品信息（调用商品服务）
        List<OrderDetail> orderDetailList = orderDTO.getOrderDetailList();
        List<String> ids = orderDetailList.stream().map(OrderDetail::getProductId)
                .collect(Collectors.toList());

        List<ProductInfoOutput> productList = productClient.getProductInfoByIds(ids);

        if (productList.isEmpty()) {
            throw new OrderException(OrderExceptionEnum.PRODUCT_NOT_EXIT.getCode(),
                    OrderExceptionEnum.PRODUCT_NOT_EXIT.getMessage());
        } else if (productList.size() != orderDetailList.size()) {
            throw new OrderException(OrderExceptionEnum.PRODUCT_NOT_EXIT.getCode(),
                    OrderExceptionEnum.PRODUCT_NOT_EXIT.getMessage());
        }

        BigDecimal count = new BigDecimal(0);
        // 计算总价
        for (ProductInfoOutput p : productList) {
            for (OrderDetail orderDetail : orderDetailList) {
                if (Objects.equals(orderDetail.getProductId(), p.getProductId())) {
                    count = (p.getProductPrice().multiply(new BigDecimal(orderDetail.getProductQuantity()))).add(count);
                    BeanUtils.copyProperties(p, orderDetail);
                    orderDetail.setOrderId(orderDTO.getOrderId());
                    orderDetail.setDetailId(KeyUtil.genUniqueKey());
                    detailRepository.save(orderDetail);
                }
            }
        }
        // 扣库存（调用商品服务）
        List<DecreaseStockInput> decreaseStockInputs = orderDetailList.stream()
                .map(d -> new DecreaseStockInput(d.getProductId(), d.getProductQuantity())).collect(Collectors.toList());

        try {
            productClient.reduceProductStock(decreaseStockInputs);
        } catch (Exception e) {
            throw new OrderException(OrderExceptionEnum.PRODUCT_STOACK.getCode(),
                    OrderExceptionEnum.PRODUCT_STOACK.getMessage());
        }

        //订单入库
        OrderMaster orderMaster = new OrderMaster();
        BeanUtils.copyProperties(orderDTO, orderMaster);
        orderMaster.setOrderAmount(count);
        orderMaster.setOrderStatus(OrderStatusEnum.NEW.getStatus());
        orderMaster.setPayStatus(OrderPayStatusEnum.NO_PAY.getStatus());
        masterRepository.save(orderMaster);

        orderDTO.setOrderId(orderMaster.getOrderId());

        return orderDTO;
    }

    /**
     * 订单存在，则修改其状态
     * @param orderId
     * @param status
     */
    @Override
    public void changeOrderStatus(String orderId, int status) {
        Optional<OrderMaster> orderMasterOptional = masterRepository.findById(orderId);
        boolean present = orderMasterOptional.isPresent();
        if(!present){
            throw new OrderException(OrderExceptionEnum.ORDER_ITEM_NOT_EXIT.getCode(),
                    OrderExceptionEnum.ORDER_ITEM_NOT_EXIT.getMessage());
        }
        OrderMaster orderMaster = orderMasterOptional.get();
        orderMaster.setOrderStatus(status);
        masterRepository.save(orderMaster);
    }



/*  TestTempalte实现
    @Override
    @Transactional
    public OrderDTO create(OrderDTO orderDTO) {
        String orderId = KeyUtil.genUniqueKey();
        //查询商品信息（调用商品服务）
        List<OrderDetail> orderDetailList = orderDTO.getOrderDetailList();

        List<String> ids = orderDetailList.stream().map(OrderDetail::getProductId).collect(Collectors.toList());

        String url = "http://PRODUCT/getPordutsByIds";
        RequestEntity<List<String>> request = null;
        try {
            request = RequestEntity
                    .post(new URI(url))
                    .accept(MediaType.APPLICATION_JSON)
                    .contentType(MediaType.APPLICATION_JSON)
                    .body(ids);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        ResponseEntity<List<ProductInfo>> listResponseEntity = restTemplate.exchange(url,
                HttpMethod.POST, request, new ParameterizedTypeReference<List<ProductInfo>>() {
                });


        List<ProductInfo> productList = listResponseEntity.getBody();
        if (productList.isEmpty()) {
            throw new OrderException(OrderExceptionEnum.PRODUCT_NOT_EXIT.getCode(),
                    OrderExceptionEnum.PRODUCT_NOT_EXIT.getMessage());
        } else if (productList.size() != orderDetailList.size()) {
            throw new OrderException(OrderExceptionEnum.PRODUCT_NOT_EXIT.getCode(),
                    OrderExceptionEnum.PRODUCT_NOT_EXIT.getMessage());
        }

        BigDecimal count = new BigDecimal(0);
        // 计算总价
        for (ProductInfo p : productList) {
            for (OrderDetail orderDetail : orderDetailList) {
                if (Objects.equals(orderDetail.getProductId(), p.getProductId())) {
                    count = (p.getProductPrice().multiply(new BigDecimal(orderDetail.getProductQuantity()))).add(count);
                    BeanUtils.copyProperties(p, orderDetail);
                    orderDetail.setOrderId(orderId);
                    orderDetail.setDetailId(KeyUtil.genUniqueKey());
                    detailRepository.save(orderDetail);
                }
            }
        }
        // 扣库存（调用商品服务）
        List<CartDTO> cartDTOS = orderDetailList.stream()
                .map(d -> new CartDTO(d.getProductId(), d.getProductQuantity())).collect(Collectors.toList());

        ResponseEntity<ResultVO> responseEntity = restTemplate.postForEntity("http://PRODUCT/reduceProductStock",
                cartDTOS, ResultVO.class);
        if (responseEntity.getStatusCode().isError()) {
            throw new OrderException(4, "库存不足");
        }

        //订单入库
        OrderMaster orderMaster = new OrderMaster();
        BeanUtils.copyProperties(orderDTO, orderMaster);
        orderMaster.setOrderId(orderId);
        orderMaster.setOrderAmount(count);
        orderMaster.setOrderStatus(OrderStatusEnum.NEW.getStatus());
        orderMaster.setPayStatus(OrderPayStatusEnum.NO_PAY.getStatus());
        masterRepository.save(orderMaster);
        orderDTO.setOrderId(orderMaster.getOrderId());
        return orderDTO;
    }*/
}